﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RooHui.Infrastructure.Entities.Entity;
using RooHui.Tool;
using System.Drawing;
using System.IO;

namespace RooHui.Admin.Web.Controllers
{
    public class ResourceController : Controller
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="mode">0：图片展示 1：文件下载</param>
        public void Get(int id,int mode)
        {
            var resource = new Resource().Find(id.ToString());
            if (resource != null)
            {
                if (resource.PrivateLevel == Infrastructure.Entities.Enum.PrivateLevel.Private)
                {
                    if (!HttpContext.User.Identity.IsAuthenticated ||
                        HttpContext.User.Identity.Name.ToLower() != resource.CreateUser.ToLower())
                    {
                        return;
                    }
                }
                else if (resource.PrivateLevel == Infrastructure.Entities.Enum.PrivateLevel.MemberOnly)
                {
                    if (!HttpContext.User.Identity.IsAuthenticated)
                    {
                        return;
                    }
                }
                else
                {
                    if (mode == 0)
                    {
                        var filePath = Server.MapPath(resource.Path);
                        if (System.IO.File.Exists(filePath))
                        {
                            using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                            {
                                byte[] stream = new byte[fs.Length];
                                fs.Read(stream, 0, (int)fs.Length);
                                var httpContext = System.Web.HttpContext.Current;
                                httpContext.Response.ClearContent();
                                httpContext.Response.ContentType = "image/Png";
                                httpContext.Response.BinaryWrite(stream);
                            }
                        }
                        else
                        { 
                            
                        }
                    }
                    else if (mode == 1)
                    {
                        FileDownLoad.DownLoadFile(
                            System.Web.HttpContext.Current.Request,
                            System.Web.HttpContext.Current.Response,
                            resource.Path);
                    }
                }
            }
        }

    }
}
